#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : chat_model 
# @File    : session_knowledge_logic.py
# @IDE     : PyCharm 
# @Author  :ZH
# @Time    : 2025/1/15 11:36
__all__ = ['session_knowledge_logic']

from typing import List

from tortoise.expressions import Q

from apps import cruds
from apps.models import User, SessionKnowledge


class SessionKnowledgeLogic:
    def __init__(self):
        self.crud = cruds.session_knowledge_crud

    async def all_session_knowledge(self, session_id: int, user: User):
        return await self.crud.get_all(
            is_delete=False, session_id=session_id, user_id=user.id
        )

    async def create_session_knowledge(self, session_id: int, knowledge_ids: List[int], user: User):
        all_ = await self.all_session_knowledge(session_id=session_id, user=user)
        insert_data = []
        if all_:
            for i in all_:
                if i.knowledge_id in knowledge_ids:
                    continue
                if i.knowledge_id not in knowledge_ids:
                    i.is_delete = True
                    await i.save()
            insert_data += [
                {
                    'session_id': session_id,
                    'knowledge_id': i,
                    'user_id': user.id
                }
                for i in knowledge_ids if i not in [z.knowledge_id for z in all_]
            ]
        else:
            # 创建数据进行添加
            insert_data += [
                {
                    'session_id': session_id,
                    'knowledge_id': i,
                    'user_id': user.id
                }
                for i in knowledge_ids
            ]
        if insert_data:
            await self.crud.model.bulk_create([
                SessionKnowledge(**i)
                for i in insert_data
            ])

    async def delete_all_session_knowledge(self, session_id: int, user: User):
        await self.crud.update(obj_in={'is_delete': True}, session_id=session_id, user_id=user.id, is_delete=False)


session_knowledge_logic = SessionKnowledgeLogic()
